var AjaxCrud = QualityCheck.AjaxCRUD;
var serverUrl = QualityCheck.GPUD.ServiceConfig;
//var currentPage = 1;
//var pageSize = 10;
var map = null;
var toolbar = null;
var scale = null;
var circle = {};
var pointMarker = {};//轨迹点对象
var poly = {};
var cluster = null;
var style = {
        color:'red',
        fillColor:'yellow',
        fillOpacity:0.2,
        weight:3
    };
var style1 = {
        color:'red',
        fillColor:'blue',
        fillOpacity:0.2,
        weight:3
    };
var style2 = {
        color:'blue',
        fillColor:'yellow',
        fillOpacity:0.2,
        weight:3
    };
var style3 = {
        color:'blue',
        fillColor:'red',
        fillOpacity:0.2,
        weight:3
    };
$(function(){
	initPages();
	window.onresize = function () {
		initPages();
	};
	initMap();
	pageBtns();
	pointPantoStudent();
});
function initMap(){
	map = new AMap.Map("map",{
		level:15,//设置地图缩放级别
	});
	map.plugin(["AMap.ToolBar","AMap.OverView","AMap.Scale"],function(){ 
		toolbar = new AMap.ToolBar();
		toolbar.autoPosition=false; //加载工具条 
		map.addControl(toolbar);  	
		scale = new AMap.Scale(); //加载比例尺
		map.addControl(scale);
	});
	map.setDefaultCursor("url(http://developer.amap.com/wp-content/uploads/2014/06/closedhand.cur),pointer");
	$(".amap-logo").hide();
	$(".amap-copyright").hide();
	$(".amap-container").css("position","absolute");
}
function getNowCity(){
	  //加载城市查询插件
  AMap.service(["AMap.CitySearch"], function() {
      //实例化城市查询类
      var citysearch = new AMap.CitySearch();
      //自动获取用户IP，返回当前城市
      citysearch.getLocalCity(function(status, result) {
          if (status === 'complete' && result.info === 'OK') {
              if (result && result.city && result.bounds) {
                  var citybounds = result.bounds;
                  //地图显示当前城市
                  map.panTo(new AMap.LngLat(citybounds.getCenter().lng,citybounds.getCenter().lat));
              }
          }
      });
  });
}

function pointPantoStudent(){
	for(var key in pointMarker){
		if(pointMarker[key]){
			pointMarker[key].setMap(null);
		}
	}
	var userKey = $("#user-name",parent.parent.document).attr("key");
	var classcode = $(".classes-choice-select",parent.document).attr("classcode");
	var data = {
			cmd:"teacherGetStudentsPosition",
			model:"position",
			userKey:userKey,
			data:{
				classcode:classcode
			},
			remark:""
	};
	AjaxCrud.get2(serverUrl.ServerLoginUrl,data,function(res){
		map.clearInfoWindow();
		cachedatas = res;
		initStudentTable();
		if(res.result == 1 && res.data != undefined && res.data != ""){
			var data = res.data;
			if(data.length > 0){
				for(var i = 0; i < data.length; i++){
					if(data[i].lonLat != null){
						var pointArr = data[i].lonLat.split(",");
						var y = pointArr[0];
						var x = pointArr[1];
						var showObj = {};
						showObj["学生"] = data[i].studentname;
						showObj["IMEI"] = data[i].imei;
						showObj["数据时间"] = data[i].time;
						showObj["手机"] = data[i].cellphone;
						if(data[i].address != null){
							showObj["当前位置"] = data[i].address;
						}else{
							showObj["当前位置"] = "暂时不能定位到准确地点";
						}
						var imgUrl = "";
						if(data[i].type == 0 || data[i].type == "0"){
							imgUrl = '../../../../img/position/lixian.png';
							showObj["定位方式"] = "离线";
						}else if(data[i].type == 1 || data[i].type == "1"){
							imgUrl = '../../../../img/position/beidou.png';
							showObj["定位方式"] = "北斗定位";
						}else if(data[i].type == 2 || data[i].type == "2"){
							imgUrl = '../../../../img/position/shinei.png';
							showObj["定位方式"] = "蓝牙定位";
							var roomD = JSON.parse(data[i].remark);
							showObj["室内地图"] = "<a href='javascript:void(0);' onClick=\"enterRoom('"+roomD.scale+"','"+roomD.x+"','"+roomD.y+"','"+roomD.build_name + roomD.floor+"','"+roomD.build_id+"','"+roomD.floor+"','"+showObj["学生"]+"','"+showObj["手机"]+"');\" class='enter-room'>进入</a>";
						}else if(data[i].type == 3 || data[i].type == "3"){
							imgUrl = '../../../../img/position/jizhan.png';
							showObj["定位方式"] = "基站定位";
						}
						showObj["终端电量"] = "<img src='../../../../img/position/power_"+ data[i].power +".png' style='padding-top:5px;'/>";
						var icon = new AMap.Icon({
							size:new AMap.Size(40,40),//图标大小
							image:imgUrl,//大图地址
							imageSize:new AMap.Size(40,40)
						});
						addMarker(x,y,icon,showObj,data[i].imei);
						map.panTo(new AMap.LngLat(y,x));
						
					}
				}
				if (cluster) {
			        cluster.setMap(null);
			    }
				map.plugin(["AMap.MarkerClusterer"], function () {
					cluster = new AMap.MarkerClusterer(map, markers);
		        });
			}else{
				getNowCity();
			}
		}else{
			getNowCity();
		}
	},null,null);
}
function pageData(data,currentpage,pagesize){
	var start = (currentpage-1)*pagesize;
	var end = currentpage*pagesize-1;
	var datas = data.slice(start,end);
	return datas;
};
function initStudentTable(){
//	currentPage = currentpage;
	var res = cachedatas;
	var content = "";
	if(res.result == 1){
		if(res.data != undefined && res.data != ""){
			var data = res.data;
//			var total = res.data.length;
//			totalPage = Math.ceil(total/pageSize);
//			$("#total-page").text(totalPage);
//			$("#now-page").text(currentpage);
			if(data.length > 0){
				for(var i = 0; i < data.length; i++){
					for(var key in data[i]){
						if(data[i][key] == null || data[i][key] == undefined){
							data[i][key] = "";
						}
					}
					content += "<div class=\"data-trs-show\" indexs = '"+i+"'  lnglat = \""+data[i].lonLat+"\">" +
					"<div class=\"pdata-name\" style='width:190px;' title='"+data[i].studentname+"'>"+substr(data[i].studentname,8)+"</div>" +
					"<div class=\"pdata-class\" style='width:190px;'>" + data[i].familyphone + "</div>" +
					"<div class=\"pdata-add\" style='width:190px;' title=\""+data[i].address+"\">" + substr(data[i].address,12) + "</div>" +
					"</div>";
				}
				$(".left-datas-show").empty();
				$(".left-datas-show").append(content);
				
				$(".data-trs-show").click(function(){
					map.clearInfoWindow();
					var lonLat = $(this).attr("lnglat");
					var index = $(this).attr("indexs");
					var nowData = data[index];
					var pointArr = lonLat.split(",");
					var x = pointArr[0];
					var y = pointArr[1];
					var showObj = {};
					showObj["学生"] = nowData.studentname;
					showObj["IMEI"] = nowData.imei;
					showObj["数据时间"] = nowData.time;
					if(nowData.address != null){
						showObj["当前位置"] = nowData.address;
					}else{
						showObj["当前位置"] = "暂时不能定位到准确地点";
					}
					var imgUrl = "";
					if(nowData.type == 0 || nowData.type == "0"){
						imgUrl = '../../../../img/position/lixian.png';
						showObj["定位方式"] = "离线";
					}else if(nowData.type == 1 || nowData.type == "1"){
						imgUrl = '../../../../img/position/beidou.png';
						showObj["定位方式"] = "北斗定位";
					}else if(nowData.type == 2 || nowData.type == "2"){
						imgUrl = '../../../../img/position/shinei.png';
						showObj["定位方式"] = "蓝牙定位";
						var roomD = JSON.parse(nowData.remark);
						showObj["室内地图"] = "<a href='javascript:void(0);' onClick=\"enterRoom('"+roomD.scale+"','"+roomD.x+"','"+roomD.y+"','"+roomD.build_name + roomD.floor+"','"+roomD.build_id+"','"+roomD.floor+"','"+showObj["学生"]+"','"+showObj["手机"]+"');\" class='enter-room'>进入</a>";
					}else if(nowData.type == 3 || nowData.type == "3"){
						imgUrl = '../../../../img/position/jizhan.png';
						showObj["定位方式"] = "基站定位";
					}
					var icon = new AMap.Icon({
						size:new AMap.Size(40,40),//图标大小
						image:imgUrl,//大图地址
						imageSize:new AMap.Size(40,40)
					});
					addMarker2(y,x,icon,showObj,"high-icon");
					map.panTo(new AMap.LngLat(x,y));
				});
				
			}else{
				content += "<div class='no-res-show'>未查询到相关数据！</div>";
				$(".left-datas-show").empty();
				$(".left-datas-show").append(content);
			}
		}else{
			content += "<div class='no-res-show'>未查询到相关数据！</div>";
			$(".left-datas-show").empty();
			$(".left-datas-show").append(content);
		}
		processEnd("加载成功");
	}else{
		content += "<div class='no-res-show'>未查询到相关数据！</div>";
		$(".left-datas-show").empty();
		$(".left-datas-show").append(content);
		processError("加载失败");
	}
}
function enterRoom(scale,x,y,name,buildid,floor,stuname,stuphone){
	$(".index-dialog-cover",top.document).show();
	$(".room-map-dialog",top.document).show();
	var imgUrl = "schoolimg/"+buildid+"-"+floor.toUpperCase()+".jpg";
	new RoomMap.initMap($("#room-map",top.document),scale,imgUrl);
	if(stuphone == undefined || stuphone == "undefined"){
		stuphone = "";
	}
	RoomMap.addPoint(x,y,"img/img.png",{
		title:stuname,
		height:100,
		contents :"<div class='di-le-na'>姓名</div><div class='di-ri-va'>"+stuname+"</div>" +
		"<div class='di-le-na'>当前位置</div><div class='di-ri-va'>"+name.toUpperCase()+"</div>",
	});
}
var markers = [];
//添加点方法并注册线点击事件
function addMarker(x,y,icon,obj,name){
	if(pointMarker[name]){
		pointMarker[name].setMap(null);
	}
	pointMarker[name] = new AMap.Marker({
		id:name,
		position:new AMap.LngLat(y,x),
		icon:icon, //marker图标
		offset:{x:-20,y:-40} //相对于基点的位置
	});
	pointMarker[name].setMap(map);
    clickLayer(pointMarker[name],function(){
    	var content = "<table>";
	    for(key in obj){
	    	if(key == "数据时间"){
	    		if(obj[key].toString().indexOf("-") < 0){
	    			obj[key] = getSmpFormatDateByLong(parseInt(obj[key])*1000,true);
	    		}
	    	}
	        content += "<tr><td style='text-align: right;font-weight:700;width:40%;font-size:15px;'>"+key+"：</td><td style='font-size:15px;'>"+obj[key]+"</td></tr>";
	    }
	    content += "</table>";
	    map.clearInfoWindow();
	    var inforWindow = new AMap.InfoWindow({
			offset:new AMap.Pixel(0,-26),
			content:content
		});
	    inforWindow.open(map,pointMarker[name].getPosition());
    });
}
function addMarker2(x,y,icon,obj,name){
	if(pointMarker[name]){
		pointMarker[name].setMap(null);
	}
	pointMarker[name] = new AMap.Marker({
		id:name,
		position:new AMap.LngLat(y,x),
		icon:icon, //marker图标
		offset:{x:-20,y:-40} //相对于基点的位置
	});
	pointMarker[name].setMap(map);
    clickLayer(pointMarker[name],function(){
    	var content = "<table>";
	    for(key in obj){
	    	if(key == "数据时间"){
	    		if(obj[key].toString().indexOf("-") < 0){
	    			obj[key] = getSmpFormatDateByLong(parseInt(obj[key])*1000,true);
	    		}
	    	}
	        content += "<tr><td style='text-align: right;font-weight:700;width:40%;'>"+key+"：</td><td>"+obj[key]+"</td></tr>";
	    }
	    content += "</table>";
	    map.clearInfoWindow();
	    var inforWindow = new AMap.InfoWindow({
			offset:new AMap.Pixel(0,-26),
			content:content
		});
	    inforWindow.open(map,pointMarker[name].getPosition());
    });
}
function clickLayer(layer,method){
	AMap.event.addListener(layer, "click", method);
}

function pageBtns(){
	$(".classes-choice",parent.document).unbind("click");
	$(".classes-choice",parent.document).click(function(){
		$(".classes-choice",parent.document).removeClass("classes-choice-select");
		$(this).addClass("classes-choice-select");
		pointPantoStudent();
	});	
	window.setInterval(pointPantoStudent, 30*1000);
}
function substr(str,len){
	if(str != undefined){
		if(str.length > len){
			str = str.substring(0,len-2)+"...";
			return str;
		}else{
			return str;
		}
	}else{
		return "";
	}
}
function initPages(){
	var bodyRW = $("#aposition-body",parent.document).width() - $(".left-data-show").width();
	$("#map").width(bodyRW);		
	
	var leftDH = $(".left-data-show").height() - $(".left-datas-page").height() - 15;
	$(".left-datas-show").height(leftDH);
}